package com.example.mongodb.mongodb.controller.rabbitmq.zhifu;

import com.example.mongodb.mongodb.entity.OrderInfo;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.*;

/**
 * 实现死信队列，TTL
 */
@Controller
public class ZhiFuController {

    private static JedisCluster jedisCluster;

    /**
     * 初始化redis cluster
     */
    static {
        JedisPoolConfig config = new JedisPoolConfig();
        Set<HostAndPort> nodeList = new HashSet<>();
        nodeList.add(new HostAndPort("47.99.154.243", 6380));
        nodeList.add(new HostAndPort("47.99.154.243", 6381));
        nodeList.add(new HostAndPort("47.99.154.243", 6382));
        nodeList.add(new HostAndPort("123.207.179.78", 6383));
        nodeList.add(new HostAndPort("123.207.179.78", 6384));
        nodeList.add(new HostAndPort("123.207.179.78", 6385));
        jedisCluster = new JedisCluster(nodeList, 3000, config);

    }


@Autowired
public RabbitTemplate rabbitTemplate;


    @GetMapping("/zhifu")
    public String zhifu(Model model){
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderId(UUID.randomUUID().toString());
        orderInfo.setAddress("深圳市福田区");
        orderInfo.setMoney("20090");
        orderInfo.setPhone("18671878778");
        orderInfo.setProjectName("图纸");
        orderInfo.setUrl("https://seopic.699pic.com/photo/50055/8254.jpg_wh1200.jpg");


        //返回支付成功页面
        int i = RandomUtils.nextInt(3, 8);
        if(i<5){

            rabbitTemplate.convertAndSend("zhengChangExchange","zhifu",orderInfo.toString());

            jedisCluster.set("orders",orderInfo.toString());

            return "success";
        }else{
            //否则放入死信队列
            String orders1 = jedisCluster.get("orders");
            System.out.println(orders1);

            List<OrderInfo> orders = new ArrayList<>();
            orders.add(orderInfo);
            model.addAttribute("orders",orders);
            return "list";
        }

    }
}
